/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.spi.supports;

import com.swapper.json.*;
import com.swapper.reflect.TypeHelper;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * The array wrapper factory.
 *
 * @see Class#isArray()
 * @see java.lang.reflect.GenericArrayType
 */
public enum ArrayWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    Type componentType = TypeHelper.getArrayComponentType(type);
    if (componentType != null) {
      JsonWrapper<?> componentWrapper = context.findWrapper(componentType);
      return new ArrayWrapper(TypeHelper.getRawType(componentType), componentWrapper);
    }
    return null;
  }

  private static final class ArrayWrapper<T, C> implements JsonWrapper<T> {
    private final Class<? super C> _componentType;
    private final JsonWrapper<C> _componentWrapper;

    public ArrayWrapper(Class<? super C> componentType, JsonWrapper<C> componentWrapper) {
      _componentType = Objects.requireNonNull(componentType);
      _componentWrapper = Objects.requireNonNull(componentWrapper);
    }

    @SuppressWarnings("unchecked")
    @Override
    public JsonValue wrap(T value) {
      if (value == null) {
        return JsonValue.NULL;
      }
      int length = Array.getLength(value);
      List<JsonValue> values = new ArrayList<>(length);
      for (int i = 0; i < length; ++i) {
        C component = (C) Array.get(value, i);
        values.add(_componentWrapper.wrap(component));
      }
      return new JsonArray(values);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      }
      JsonArray jsonArray = value.toJsonArray();
      int length = jsonArray.size();
      Object array = Array.newInstance(_componentType, length);
      for (int i = 0; i < length; ++i) {
        C component = _componentWrapper.unwrap(jsonArray.get(i));
        Array.set(array, i, component);
      }
      return (T) array;
    }
  }
}
